let { jwt, jwtKey } = require('../server_jwt');
let express = require('express');
let router = express.Router();
let xss = require('xss')
let db = require('../db');

// 这个接口用于返回用户的详细资料(用户名、用户性别、用户发的动态（图片、文字）、用户获赞总数)
router.get('/userDetail', (req, res) => {
    const token = req.headers['authorization'];
    jwt.verify(token, jwtKey, (err, decoded) => {
        if (err) {
            res.send({ msg: "登录验证失败，请重新登录", login: false });
        } else if (parseInt(+new Date() / 1000) >= decoded.exp) {
            res.send({ msg: "登录超时:", login: false });
        }

        let sql_dynamic = `SELECT
        u.sex,
        u.username,
        u.profile,
        u.user_icon,
        p.intor AS text,
        p.imgList AS image,
        (SELECT COUNT(*) FROM upvote WHERE postID IN (SELECT postID FROM post WHERE uid = u.uid)) AS total_upvotes
    FROM
        users u
    LEFT JOIN
        post p ON u.uid = p.uid
    WHERE
        u.uid = ?; `;
        let uid = decoded.uid;
        db.query(sql_dynamic, uid, (err, result) => {
            if (err) {
                res.send({ msg: "查询失败", login: true });
            } else {
                res.send(result);
            }
        });

    });
})

// 这个端口用于获取用户的名字、性别、头像、简介
router.get('/userBrief', (req, res) => {
    const token = req.headers['authorization'];
    jwt.verify(token, jwtKey, (err, decoded) => {
        if (err) {
            res.send({ msg: "登录验证失败，请重新登录", login: false });
        } else if (parseInt(+new Date() / 1000) >= decoded.exp) {
            res.send({ msg: "登录超时:", login: false });
        }
        let sql_brief = 'SELECT username, sex, user_icon, profile FROM users WHERE uid = ?';
        db.query(sql_brief,decoded.uid, (err, result) =>{
            if (err) {
                res.send({ msg: "查询失败", login: true });
            } else {
                res.send(result);
            }
        })
    });
});

//  这个端口用来更新用户头像的
router.post('/updateImg', (req, res) => {
    const token = req.headers['authorization'];
    jwt.verify(token, jwtKey, (err, decoded) => {
        if (err) {
            res.send({ msg: "登录验证失败，请重新登录", login: false });
        } else if (parseInt(+new Date() / 1000) >= decoded.exp) {
            res.send({ msg: "登录超时:", login: false });
        }

        sql_updateImg = `UPDATE users SET user_icon = ? WHERE uid = ?;`;
        img = req.body.img;
        uid = decoded.uid;
        db.query(sql_updateImg, [img, uid], (err) => {
            if (err) {
                res.send({ msg: "头像更换失败", login: true });
            } else {
                res.send({ msg: "头像更换成功", login: true });
            }
        });
    });
});


// 这个接口拿来更新用户名的
router.post('/updateUsername', (req, res) =>{
    const token = req.headers['authorization'];
    jwt.verify(token, jwtKey, (err, decoded) => {
        if (err) {
            res.send({ msg: "登录验证失败，请重新登录", login: false });
        } else if (parseInt(+new Date() / 1000) >= decoded.exp) {
            res.send({ msg: "登录超时:", login: false });
        }

        let name = xss(req.body.username);
        sql_updateName = 'UPDATE users set username = ? where uid = ?'
        db.query(sql_updateName, [name, decoded.uid], (err)=>{
            if (err) {
                res.send({ msg: "用户名更新失败", login: true });
            } else {
                res.send({ msg: "用户名更新成功", login: true });
            }
        });
    });
});

// 这个接口拿来更新用户简介的
router.post('/updateBrief', (req, res) => {
    const token = req.headers['authorization'];
    jwt.verify(token, jwtKey, (err, decoded) => {
        if (err) {
            res.send({ msg: "登录验证失败，请重新登录", login: false });
        } else if (parseInt(+new Date() / 1000) >= decoded.exp) {
            res.send({ msg: "登录超时:", login: false });
        }
        let brief = xss(req.body.brief);

        console.log(decoded.uid);
        console.log(brief);
        sql_updataBrief = 'UPDATE users SET profile = ? WHERE uid = ?'
        db.query(sql_updataBrief,[brief, decoded.uid], (err)=>{
            if (err) {
                res.send({ msg: "简介更新失败", login: true });
            } else {
                res.send({ msg: "简介更新成功", login: true });
            }
        });
    });
});

module.exports = router;